// 渲染图表 echarts3
klcs.chartRender = function (totalId, option) {
    var proChart = null;

    var total = document.getElementById(totalId)


    // this.barChart.dispose();
    // console.log(total,111)
    if (!total) {
        return;
    }
    // 这里需要原生dom节点
    proChart = echarts.init(total);

    // 没有这个重新渲染,没反应.
    proChart.dispose();
    proChart = echarts.init(total);
    //传入参数
    proChart.setOption(option, true);

    var debounce = klcs.debounce(function () {
        proChart.resize();
        // console.log(11111,222222222222222)

    }, 300)

    // 重绘机制
    window.addEventListener("resize", function () {
        debounce();
    });

    return proChart;
};


// 定义柱状图右侧以及顶部图形元素
klcs.extendShapeRightRect = {
    shape: {
        x: 0,
            y: 0,
                width: 18,
                    zWidth: 15,
                        zHeight: 8
    },
    buildPath: function (ctx, shape) {
        const api = shape.api;
        const xAxisPoint = api.coord([shape.xValue, 0]);
        const p1 = [shape.x - shape.width / 2, shape.y - shape.zHeight / 2];
        const p3 = [xAxisPoint[0] + shape.width / 2, xAxisPoint[1]];
        const p4 = [shape.x + shape.width / 2, shape.y];
        const p5 = [xAxisPoint[0] + shape.width / 2 + shape.zWidth, xAxisPoint[1]];
        const p6 = [
            shape.x + shape.width / 2 + shape.zWidth,
            shape.y - shape.zHeight / 2
        ];
        const p7 = [
            shape.x - shape.width / 2 + shape.zWidth,
            shape.y - shape.zHeight
        ];
        ctx.moveTo(p4[0], p4[1]);
        ctx.lineTo(p3[0], p3[1]);
        ctx.lineTo(p5[0], p5[1]);
        ctx.lineTo(p6[0], p6[1]);
        ctx.lineTo(p4[0], p4[1]);

        ctx.moveTo(p4[0], p4[1]);
        ctx.lineTo(p6[0], p6[1]);
        ctx.lineTo(p7[0], p7[1]);
        ctx.lineTo(p1[0], p1[1]);
        ctx.lineTo(p4[0], p4[1]);
        ctx.closePath();
    }
}

klcs.extendShapeLeftRect = {
    shape: {
        x: 0,
            y: 0,
                width: 19, //柱状图宽
                    zWidth: 8, //阴影折角宽
                        zHeight: 4 //阴影折角高
    },
    buildPath: function (ctx, shape) {
        const api = shape.api;
        const xAxisPoint = api.coord([shape.xValue, 0]);
        const p0 = [shape.x - shape.width / 2, shape.y - shape.zHeight];
        const p1 = [shape.x - shape.width / 2, shape.y - shape.zHeight];
        const p2 = [xAxisPoint[0] - shape.width / 2, xAxisPoint[1]];
        const p3 = [xAxisPoint[0] + shape.width / 2, xAxisPoint[1]];
        const p4 = [shape.x + shape.width / 2, shape.y];

        ctx.moveTo(p0[0], p0[1]);
        ctx.lineTo(p1[0], p1[1]);
        ctx.lineTo(p2[0], p2[1]);
        ctx.lineTo(p3[0], p3[1]);
        ctx.lineTo(p4[0], p4[1]);
        ctx.lineTo(p0[0], p0[1]);
        ctx.closePath();
    }
}

klcs.getSeriesData = function (seriesData, colors) {
    const data = [];
    seriesData.forEach((item, index) => {
        data.push(
            {
                type: 'custom',
                name: item.label,
                renderItem: function (params, api) {
                    return klcs.getRenderItem(params, api);
                },
                data: item.value,
                itemStyle: {
                    color: () => {
                        return new echarts.graphic.LinearGradient(0, 0, 0, 1, colors[index]);
                    },
                },
            }
        )
    })
    return data
}

klcs.getlegendData = function (labels, colors) {
    const data = [];
    labels.forEach((item, index) => {
        data.push(
            {
                name: item,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, colors[index]),
                },
            }
        )
    })
    return data
}

klcs.getRenderItem = function(params, api) {
    const index = params.seriesIndex;
    let location = api.coord([api.value(0) + index, api.value(1)]);
    var extent = api.size([0, api.value(1)]);
    return {
        type: 'group',
        children: [
            {
                type: 'leftRect',
                shape: {
                    api,
                    xValue: api.value(0) + index,
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1]
                },
                style: api.style()
            },
            {
                type: 'rightRect',
                shape: {
                    api,
                    xValue: api.value(0) + index,
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1]
                },
                style: api.style()
            }
        ]
    };
}

// 生成模拟 3D 饼图的配置项, internalDiameterRatio = 为空心圆的半径/外圆的半径
klcs.getPie3D = function(pieData, internalDiameterRatio) {
    const series = []
    let sumValue = 0
    let startValue = 0
    let endValue = 0
    const legendData = []
    const k =
        typeof internalDiameterRatio !== 'undefined'
            ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
            : 1 / 3

    // 为每一个饼图数据，生成一个 series-surface 配置
    for (let i = 0; i < pieData.length; i++) {
        sumValue += pieData[i].value

        const seriesItem = {
            name:
                typeof pieData[i].name === 'undefined'
                    ? `series${i}`
                    : pieData[i].name,
            type: 'surface',
            parametric: true,
            wireframe: {
                show: false
            },
            pieData: pieData[i],
            pieStatus: {
                selected: false,
                hovered: false,
                k: k
            }
        }

        if (typeof pieData[i].itemStyle !== 'undefined') {
            const itemStyle = {}

            typeof pieData[i].itemStyle.color !== 'undefined'
                ? (itemStyle.color = pieData[i].itemStyle.color)
                : null
            typeof pieData[i].itemStyle.opacity !== 'undefined'
                ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
                : null

            seriesItem.itemStyle = itemStyle
        }
        series.push(seriesItem)
    }

    // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
    // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
    for (let i = 0; i < series.length; i++) {
        endValue = startValue + series[i].pieData.value
        series[i].pieData.startRatio = startValue / sumValue
        series[i].pieData.endRatio = endValue / sumValue
        series[i].parametricEquation = klcs.getParametricEquation(
            series[i].pieData.startRatio,
            series[i].pieData.endRatio,
            false,
            false,
            k,
            2000
        )

        startValue = endValue

        legendData.push(series[i].name)
    }
    return series
}

klcs.getParametricEquation = function (startRatio, endRatio, isSelected, isHovered, k, h) {
    // 计算
    let midRatio = (startRatio + endRatio) / 2;

    let startRadian = startRatio * Math.PI * 2;
    let endRadian = endRatio * Math.PI * 2;
    let midRadian = midRatio * Math.PI * 2;

    // 如果只有一个扇形，则不实现选中效果。
    if (startRatio === 0 && endRatio === 1) {
        isSelected = false;
    }

    // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
    k = typeof k !== 'undefined' ? k : 1 / 3;

    // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
    let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
    let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

    // 计算高亮效果的放大比例（未高亮，则比例为 1）
    let hoverRate = isHovered ? 1.05 : 1;

    // 返回曲面参数方程
    return {
        u: {
            min: -Math.PI,
            max: Math.PI * 3,
            step: Math.PI / 32,
        },

        v: {
            min: 0,
            max: Math.PI * 2,
            step: Math.PI / 20,
        },

        x: function (u, v) {
            if (u < startRadian) {
                return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
            }
            if (u > endRadian) {
                return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
            }
            return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        y: function (u, v) {
            if (u < startRadian) {
                return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
            }
            if (u > endRadian) {
                return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
            }
            return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        z: function (u, v) {
            if (u < -Math.PI * 0.5) {
                return Math.sin(u);
            }
            if (u > Math.PI * 2.5) {
                return Math.sin(u) * h * 0.1;
            }
            return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
        },
    };
}
// 补充一个透明的圆环，用于支撑高亮功能的近似实现。
klcs.transparentRing = {
    name: 'mouseoutSeries',
    type: 'surface',
    parametric: true,
    wireframe: {
        show: false,
    },
    itemStyle: {
        opacity: 0,
    },
    parametricEquation: {
        u: {
            min: 0,
            max: Math.PI * 2,
            step: Math.PI / 20,
        },
        v: {
            min: 0,
            max: Math.PI,
            step: Math.PI / 20,
        },
        x: function (u, v) {
            return Math.sin(v) * Math.sin(u) + Math.sin(u);
        },
        y: function (u, v) {
            return Math.sin(v) * Math.cos(u) + Math.cos(u);
        },
        z: function (u, v) {
            return Math.cos(v) > 0 ? 0.1 : -0.1;
        },
    },
}

// klcs.chartMapRender('aaa', 'HK', geoJson , option);
klcs.chartMapRender = function (totalId, name, geoJson, option) {


    var proChart = null;
    var total = document.getElementById(totalId)

    if (!total) {
        console.error('没有找到dom节点!')
        return;
    }

    // 这里需要原生dom节点
    proChart = echarts.init(total);

    echarts.registerMap(name, geoJson);


    // 没有这个重新渲染,没反应.
    proChart.dispose();
    proChart = echarts.init(total);
    //传入参数
    proChart.setOption(option, true);

    var debounce = klcs.debounce(function () {
        proChart.resize();
        // console.log(11111,222222222222222)

    }, 300)

    // 重绘机制
    window.addEventListener("resize", function () {
        debounce();
    });

    return proChart;
};

